package com.stormrage.edu.serv.learn.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.stormrage.edu.dao.exam.ExmScoreDao;
import com.stormrage.edu.dao.learn.LeaStudentDao;
import com.stormrage.edu.dao.learn.LeaStudentSelectDao;
import com.stormrage.edu.dao.learn.LeaStudentVideoDao;
import com.stormrage.edu.serv.edu.EduMajorServ;
import com.stormrage.edu.serv.edu.EduVideoServ;
import com.stormrage.edu.serv.exam.ExmScorePercentServ;
import com.stormrage.edu.serv.exam.ExmScoreServ;
import com.stormrage.edu.serv.learn.LeaStudentServ;
import com.stormrage.edu.serv.learn.LeaStudentVideoServ;
import com.stormrage.entity.edu.EduMajor;
import com.stormrage.entity.edu.EduVideo;
import com.stormrage.entity.exam.ExmScore;
import com.stormrage.entity.exam.ExmScorePercent;
import com.stormrage.entity.learn.LeaStudent;
import com.stormrage.entity.learn.LeaStudentSelect;
import com.stormrage.entity.learn.rep.LeaStudentRep;
import com.stormrage.entity.learn.rep.LeaStudentVideoRep;
import com.stormrage.entity.learn.req.LeaStudentReq;
import com.stormrage.entity.learn.req.LeaStudentVideoReq;
import com.stormrage.entity.learn.view.LeaStudentVideo;
import com.stormrage.entity.rep.ListRep;
import com.stormragetech.core.exception.StormrageTechException;
import com.stormragetech.core.util.BeanUtil;
import com.stormragetech.core.util.NumberUtil;

/**
 * @Title: LeaStudentServImpl.java
 * @Package com.stormrage.edu.serv.learn.impl
 * @Description: 学员 Service
 * @author www.stormragetech.com
 * @date 2016年4月15日
 * @version V1.0
 */
@Service
public class LeaStudentServImpl implements LeaStudentServ {

	private static final Logger logger = LoggerFactory.getLogger(LeaStudentServImpl.class);

	@Autowired
	private ExmScoreDao exmScoreDao;

	@Autowired
	private LeaStudentDao leaStudentDao;

	@Autowired
	private LeaStudentSelectDao leaStudentSelectDao;

	@Autowired
	private LeaStudentVideoDao leaStudentVideoDao;

	@Autowired
	private EduMajorServ eduMajorServ;

	@Autowired
	private EduVideoServ eduVideoServ;

	@Autowired
	private ExmScoreServ exmScoreServ;

	@Autowired
	private ExmScorePercentServ exmScorePercentServ;

	@Autowired
	private LeaStudentVideoServ leaStudentVideoServ;

	@Override
	public Integer create(final LeaStudent arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 Create 】- 开始运行 ");

		Integer index = leaStudentDao.create(arg0);

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 Create 】- 完成运行 ");
		return index;

	}

	@Override
	public void update(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 Update 】- 开始运行 ");

		LeaStudent entity = queryById(arg0);

		logger.debug(" 学员状态1 " + entity.toString());

		if (entity.getLocked().equals(0))
			entity.setLocked(1);
		else
			entity.setLocked(0);

		logger.debug(" 学员状态2 " + entity.toString());

		leaStudentDao.update(entity);

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 Update 】- 完成运行 ");

	}

	@Override
	public void delete(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 delete 】- 开始运行 ");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", arg0);

		leaStudentDao.delete(map);

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 delete 】- 完成运行 ");

	}

	@Override
	public void updateForApply(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 Update 】- 开始运行 ");

		// ------------------ 获取学员学习信息 ------------------
		LeaStudent entity = queryById(arg0);

		// ------------------ 更新学员审核状态 ------------------
		entity.setLocked(0);
		leaStudentDao.update(entity);

		// ------------------ 创建学员成绩 ------------------
		ExmScore score = ExmScore.instance(entity.getId());
		exmScoreDao.create(score);

		// ------------------ 创建学员课件 ------------------
		EduMajor major = eduMajorServ.queryByBunchId(entity.getBunchId());

		List<EduVideo> videoList = eduVideoServ.queryListByMajorId(major.getId());

		logger.debug(" 学员的课程为 " + videoList.toString());

		Iterator<EduVideo> iter = videoList.iterator();
		while (iter.hasNext()) {
			EduVideo video = iter.next();
			LeaStudentVideo stuVideo = LeaStudentVideo.instance(entity.getId(), video.getId());
			leaStudentVideoDao.create(stuVideo);
		}

		// ------------------ 创建学员选课状态 ------------------
		LeaStudentSelect stuSelect = LeaStudentSelect.instance(arg0, 0);
		leaStudentSelectDao.create(stuSelect);

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 Update 】- 完成运行 ");

	}

	@Override
	public Integer queryCountByBunchLock(final LeaStudentReq arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryCount 】- 开始运行 ");

		Map<String, Object> map = initQueryForQueryListByBunchLock(arg0);

		logger.debug(" 查询map为 " + map.toString());

		Integer count = leaStudentDao.queryCountByBunchLock(map);

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryCount 】- 完成运行 ");
		return count;

	}

	@Override
	public LeaStudent queryById(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryCount 】- 开始运行 ");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", arg0);

		LeaStudent entity = leaStudentDao.queryById(map);

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryCount 】- 完成运行 ");
		return entity;

	}

	@Override
	public ListRep queryListByBunch(final LeaStudentReq arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryCount 】- 开始运行 ");

		Map<String, Object> map = initQuery(arg0);

		Integer count = leaStudentDao.queryCountByBunch(map);

		List<LeaStudentRep> array = leaStudentDao.queryListByBunch(map);
		int seq = arg0.getPage().getStartPage() + 1;

		Iterator<LeaStudentRep> it = array.iterator();
		while (it.hasNext()) {
			LeaStudentRep entity = it.next();
			entity = LeaStudentRep.instance(entity, seq);
			seq++;
		}

		ListRep rep = ListRep.instance(count, array);

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryCount 】- 完成运行 ");
		return rep;

	}

	@Override
	public ListRep queryListByBunchLock(final LeaStudentReq arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryCount 】- 开始运行 ");

		Map<String, Object> map = initQueryForQueryListByBunchLock(arg0);

		Integer count = leaStudentDao.queryCountByBunchLock(map);

		List<LeaStudentRep> array = leaStudentDao.queryListByBunchLock(map);
		int seq = arg0.getPage().getStartPage() + 1;

		Iterator<LeaStudentRep> it = array.iterator();
		while (it.hasNext()) {
			LeaStudentRep entity = it.next();
			entity = LeaStudentRep.instance(entity, seq);
			seq++;
		}

		ListRep rep = ListRep.instance(count, array);

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryCount 】- 完成运行 ");
		return rep;

	}

	@Override
	public ListRep queryListForStudy(final LeaStudentReq arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryListForStudy 】- 开始运行 ");

		Map<String, Object> map = initQueryForQueryListByBunchLock(arg0);

		Integer count = leaStudentDao.queryCountByBunchLock(map);

		List<LeaStudentRep> array = leaStudentDao.queryListByBunchLock(map);
		int seq = arg0.getPage().getStartPage() + 1;

		Iterator<LeaStudentRep> it = array.iterator();
		while (it.hasNext()) {
			LeaStudentRep entity = it.next();

			// ------------------ 获取专业信息 ------------------
			EduMajor major = eduMajorServ.queryByBunchId(entity.getBunchId());

			String study = "0%";

			// ------------------ 单一模组 ------------------
			if (major.getModule().equals(0)) {
				LeaStudentVideoReq req = LeaStudentVideoReq.instance(entity.getId(), 0);
				List<LeaStudentVideoRep> videoArray = leaStudentVideoServ.queryListForSelectStudy(req);

				Integer studyLen = 0;
				Integer totalLen = 0;

				if (null != videoArray && videoArray.size() > 0) {

					logger.debug(" 是否运行1 ");

					Iterator<LeaStudentVideoRep> iter = videoArray.iterator();
					while (iter.hasNext()) {
						LeaStudentVideoRep rep = iter.next();
						studyLen += rep.getLen();
						totalLen += rep.getTlen();
					}

					study = NumberUtil.initPerc(
							new BigDecimal(studyLen).divide(new BigDecimal(totalLen), 2, BigDecimal.ROUND_HALF_UP),
							"%");
				}

				logger.debug(" 是否运行2 " + study);

			}
			// ------------------ 多模组 ------------------
			else {
				List<LeaStudentVideoRep> videoArray = leaStudentVideoServ.queryListForStudy(entity.getId());

				logger.debug(" 是否运行3 ");

				Integer studyLen = 0;
				Integer totalLen = 0;

				Iterator<LeaStudentVideoRep> iter = videoArray.iterator();
				while (iter.hasNext()) {
					LeaStudentVideoRep rep = iter.next();
					logger.debug(" caoa " + rep.toString());
					studyLen += rep.getLen();
					totalLen += rep.getTlen();
				}

				logger.debug(" 是否运行4 " + studyLen + " || " + totalLen);

				study = NumberUtil.initPerc(
						new BigDecimal(studyLen).divide(new BigDecimal(totalLen), 2, BigDecimal.ROUND_HALF_UP), "%");

			}

			logger.debug(" 是否运行5 ");

			entity = LeaStudentRep.instance(entity, seq, study);

			logger.debug(" entity 是 " + entity.toString());
			seq++;
		}

		ListRep rep = ListRep.instance(count, array);

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryListForStudy 】- 完成运行 ");
		return rep;

	}

	@Override
	public ListRep queryListForScore(final LeaStudentReq arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryListForScore 】- 开始运行 ");

		Map<String, Object> map = initQueryForQueryListByBunchLock(arg0);

		Integer count = leaStudentDao.queryCountByBunchLock(map);

		List<LeaStudentRep> array = leaStudentDao.queryListByBunchLock(map);
		int seq = arg0.getPage().getStartPage() + 1;

		Iterator<LeaStudentRep> it = array.iterator();
		while (it.hasNext()) {
			LeaStudentRep entity = it.next();

			// ------------------ 获取专业信息 ------------------
			ExmScore score = exmScoreServ.queryByStuId(entity.getId());

			ExmScorePercent perc = exmScorePercentServ.queryByTermId(entity.getTermId());

			Integer total = score.getExam() * perc.getExam() / 100 + score.getOper() * perc.getOper() / 100
					+ score.getUsua() * perc.getUsua() / 100;

			entity = LeaStudentRep.instance(entity, score, total, seq);

			logger.debug(" entity 是 " + entity.toString());
			seq++;
		}

		ListRep rep = ListRep.instance(count, array);

		logger.debug(" 【 Serv 】- 【 LeaStudentServ 】- 【 QueryListForScore 】- 完成运行 ");
		return rep;

	}

	private Map<String, Object> initQuery(final LeaStudentReq arg0) {

		if (null == arg0)
			return null;

		Map<String, Object> map = new HashMap<String, Object>();
		if (null != arg0.getPage()) {
			map.put("startPage", arg0.getPage().getStartPage());
			map.put("size", arg0.getPage().getSize());
		}

		if (null != arg0.getBunchId())
			map.put("bunchId", arg0.getBunchId());

		StringBuffer query = new StringBuffer("");

		if (null != arg0.getRealName() && arg0.getRealName().length() > 0) {
			query.append("c.real_name LIKE :realName AND ");
			map.put("realName", "%" + arg0.getRealName() + "%");
		}

		if (null != arg0.getLocked()) {
			query.append("a.locked = :locked AND ");
			map.put("locked", arg0.getLocked());
		}

		String sql = query.toString();
		if (null != sql && sql.length() > 0)
			map.put("query", " AND " + sql.substring(0, sql.length() - 4));
		else
			map.put("query", "");

		return map;
	}

	private Map<String, Object> initQueryForQueryListByBunchLock(final LeaStudentReq arg0) {

		if (null == arg0)
			return null;

		Map<String, Object> map = BeanUtil.initQuery(arg0.getPage());

		map.put("bunchId", arg0.getBunchId());
		map.put("locked", arg0.getLocked());

		StringBuffer query = new StringBuffer("");

		if (null != arg0.getRealName() && arg0.getRealName().length() > 0) {
			query.append("c.real_name LIKE :realName AND ");
			map.put("realName", "%" + arg0.getRealName() + "%");
		}

		String sql = query.toString();
		if (null != sql && sql.length() > 0)
			map.put("query", " AND " + sql.substring(0, sql.length() - 4));
		else
			map.put("query", "");

		return map;

	}

}
